package com.example.controller;

import com.example.pojo.User;
import com.example.service.userServicce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class MyController {

    @Autowired
    userServicce userService;

    @PostMapping("user/add")
    @ResponseBody
    public ResponseEntity<String> insertUser(@Valid User user){
        System.out.println(user.toString());
        User user1 = new User();
        user1.setName(user.getName());
        user1.setImage(user.getImage());
        user1.setEmail(user.getEmail());
        user1.setPhone(user.getPhone());
        user1.setCreateTime(new Date());
        int i = userService.insertUser(user);
        if( i > 0){
            return ResponseEntity.ok("success");
        }else{
            return ResponseEntity.badRequest().body("insert fail");
        }
    }

    @PostMapping("user/upload")
    @ResponseBody
    public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResponseEntity.badRequest().body("upload image fail");
        }else{
            String fileName = UUID.randomUUID().toString().replace("-","")+ "-" + file.getOriginalFilename();
            String filePath = "D:\\uploads\\";
            String path = filePath + fileName;
            File dest = new File(path);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            User user = new User();
            user.setId(15);
            user.setImage(path);

            if(userService.updateImage(user) > 0){
                return ResponseEntity.ok("upload success");
            }else{
                return ResponseEntity.badRequest().body("upload image fail");
            }
        }
    }

    @PostMapping("user/uploadMult")
    @ResponseBody
    public ResponseEntity<String> uploadImage(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("image");
        String filePath = "D:\\uploads\\";
        StringBuilder successMessage =new StringBuilder();
        successMessage.append("upload success:");
        StringBuilder failMessage =new StringBuilder();
        failMessage.append("upload fail:");
        for (MultipartFile file : files) {
            if(!file.isEmpty()){
                String fileName = UUID.randomUUID().toString().replace("-","") + "-" + file.getOriginalFilename();
                System.out.println(fileName);
                String path = filePath + fileName;
                System.out.println(path);
                File dest = new File(path);
                System.out.println(dest);
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdirs();
                }
                System.out.println(file.getOriginalFilename());
                file.transferTo(dest);
                successMessage.append(file.getOriginalFilename()+",");
            }else{
                failMessage.append(file.getOriginalFilename()+",");
            }
        }
        return ResponseEntity.ok().body(successMessage.toString()+"___"+failMessage.toString());
    }

    @GetMapping("download")
    public void download(HttpServletResponse response) throws Exception {
        // 文件地址，真实环境是存放在数据库中的
        User user = userService.selectById(15);
        File file = new File(user.getImage());
        String fileName = user.getImage().substring(user.getImage().indexOf("-")+1);
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + fileName);
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }


    @GetMapping({"/","index"})
    public String toIndex(){
        return "index";
    }

    @GetMapping({"toUpload"})
    public String toUpload(){
        return "upload-images";
    }

    @GetMapping({"toUploads"})
    public String toUploads(){
        return "upload-multimages";
    }
}
